from datetime import datetime
from sqlalchemy.orm import class_mapper
from enum import unique
from App.ext import db


class BaseModel(db.Model):
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    # 封装一个数据保存
    def save(self):
        try:
            db.session.add(self)
            db.session.commit()
            return True
        except Exception as e:
            print(e)
            return False

    def delete(self):
        try:
            db.session.delete(self)
            db.session.commit()
            return True
        except Exception as e:
            print(e)
            return False

    def to_dict(self, ignore_fileds=()):  # 可以忽略不提供某些字段， 元祖格式提供
        """ 对象转字典 供 return jsonify()使用 """
        columns = [c.key for c in class_mapper(self.__class__).columns if c.key not in ignore_fileds ]
        return dict((c, getattr(self, c)) for c in columns) 


class Department(BaseModel):
    """部门表"""
    __tablename__ = 'department'

    name = db.Column(db.String(50))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<部门 {} : {}>'.format(self.id, self.name)


class Employee(BaseModel):
    """员工"""
    __tablename__ = 'employee'
    name = db.Column(db.String(60))
    gender = db.Column(db.String)
    job = db.Column(db.String)
    birthdate = db.Column(db.Date)
    idcard = db.Column(db.String)
    address = db.Column(db.String)
    salary = db.Column(db.FLOAT)
    release_time = db.Column(db.DateTime)

    department_id = db.Column(db.INTEGER, db.ForeignKey('department.id'))
    department = db.relationship(
        'Department', backref=db.backref('employees', lazy='dynamic'))

    def __init__(self, name, gender, job, birthdate, idcard, address, salary, release_time=None):
        self.name = name
        self.gender = gender
        self.job = job
        self.birthdate = birthdate
        self.idcard = idcard
        self.address = address
        self.salary = salary
        self.release_time = release_time if release_time else datetime.now()

    def __repr__(self):
        return '<员工 {}:{} {} {}>'.format(self.id, self.name, self.address, self.salary)


class Goods(BaseModel):
    __tablename__ = 'goods'
    g_name = db.Column(db.String(64))
    g_price = db.Column(db.Float, default=0)
